<template>
    <div style="margin-left: 15px; margin-right: 15px; height: 100%">
        <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents" @checkbox-change="handleSelectionChange" :params="searchInfo" @custom="onCustom" style="height: 100%">
            <template #toolbar_tools>
                <vxe-input placeholder="搜索"></vxe-input>
            </template>
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5" v-hasPermi="['system:role:add']">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5" v-hasPermi="['system:role:edit']">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate(null)">修改</el-button>
                    </el-col>
                    <el-col :span="1.5" v-hasPermi="['system:role:remove']">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(null)">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <vxe-switch v-model="row['status']" size="medium" open-value="0" close-value="1" :disabled="row.roleId !== 1 ? !proxy.$auth.hasPermi('system:role:edit') : true" @change="handleStatusChange(row)"></vxe-switch>
            </template>
            <template #action="{ row }">
                <el-tooltip content="修改" placement="top" v-if="row.roleId !== 1">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:role:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top" v-if="row.roleId !== 1">
                    <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:role:remove']"></el-button>
                </el-tooltip>
                <el-tooltip content="数据权限" placement="top" v-if="row.roleId !== 1">
                    <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(row)" v-hasPermi="['system:role:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="数据授权" placement="top" v-if="row.roleId !== 1">
                    <el-button link type="primary" icon="DataBoard" @click="handleCustomDataScope(row)" v-hasPermi="['system:role:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="分配用户" placement="top" v-if="row.roleId !== 1">
                    <el-button link type="primary" icon="User" @click="handleAuthUser(row)" v-hasPermi="['system:role:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="表格配置" placement="top" v-if="row.roleId !== 1">
                    <el-button link type="primary" icon="Tools" @click="handleTableEdit(row)" v-hasPermi="['system:role:edit']"></el-button>
                </el-tooltip>
            </template>
        </vxe-grid>
        <Role :modelValue="roleModalVisible" @update:modelValue="(newValue) => (roleModalVisible = newValue)" :isUpdate="isUpdate" :record="recordRole" @close="closeRole"></Role>
        <DataScope v-model="openDataScope" :record="recordDataScope" @close="closeDataScope"></DataScope>
    </div>
</template>

<script lang="ts">
    import { defineComponent, ref, unref, reactive, getCurrentInstance } from "vue";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners, VxeGridEvents, VxeGridDefines } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import useBaseApi from "@/api/base/index";
    import { VxeDownload } from "@/utils/request";
    import Role from "./role.vue";
    import { useRouter } from "vue-router";
    import { changeRoleStatus, delRole, getRole, pageRole, deptTreeSelect } from "@/api/system/role";
    import { roleMenuTreeselect } from "@/api/system/menu";
    import DataScope from "./dataScope.vue";
    import { removeObjectNull } from "@/utils";

    export default defineComponent({
        components: {
            Role,
            DataScope,
        },
        setup() {
            const router = useRouter();
            const { proxy } = getCurrentInstance() as any;
            const { callGetOne, callModify } = useBaseApi("/print/printPanel");
            const { callGetOne: callGetOnePro } = useBaseApi("/print/printProvider");
            const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
            const xGrid = ref({} as VxeGridInstance);
            const single = ref(true);
            const multiple = ref(true);
            const isUpdate = ref(false);
            const roleModalVisible = ref(false);
            const recordRole = ref();
            const recordDataScope = ref();
            const deptOptions = ref([]);
            const openDataScope = ref(false);
            function getTableAction() {
                const tableAction = unref(xGrid);
                if (!tableAction) {
                    throw new Error("tableAction is null");
                }
                return tableAction;
            }
            const searchInfo = reactive<any>({
                bidId: 0,
            });

            const gridOptions = reactive<VxeGridProps>({
                border: true,
                resizable: true,
                showHeaderOverflow: true,
                showOverflow: true,
                highlightHoverRow: true,
                keepSource: true,
                id: "1",
                height: "auto",
                rowId: "roleId",
                customConfig: {
                    storage: true,
                },
                sortConfig: {
                    trigger: "cell",
                    remote: true,
                    multiple: true,
                },
                filterConfig: {
                    remote: true,
                },
                pagerConfig: {
                    pageSize: 10,
                    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
                    perfect: true,
                },
                formConfig: {
                    titleWidth: 100,
                    titleAlign: "right",
                    items: [
                        {
                            field: "roleName",
                            span: 5,
                            itemRender: { name: "$input", props: { placeholder: "请输入角色名称" } },
                            title: "角色名称",
                        },
                        {
                            field: "roleKey",
                            span: 5,
                            itemRender: { name: "$input", props: { placeholder: "请输入权限字符" } },
                            title: "权限字符",
                        },
                        {
                            field: "status",
                            title: "状态",
                            span: 5,
                            itemRender: {
                                name: "$select",
                                options: sys_normal_disable,
                            },
                        },
                        {
                            field: "createTime",
                            title: "创建时间",
                            span: 5,
                            itemRender: {
                                name: "ElDatePicker",
                                props: {
                                    valueFormat: "YYYY-MM-DD",
                                    type: "daterange",
                                    rangeSeparator: "-",
                                    startPlaceholder: "开始日期",
                                    endPlaceholder: "结束日期",
                                },
                            },
                        },
                        {
                            itemRender: {
                                name: "$buttons",
                                children: [
                                    {
                                        props: {
                                            type: "submit",
                                            content: "查询",
                                            status: "primary",
                                        },
                                    },
                                    {
                                        props: {
                                            type: "reset",
                                            content: "重置",
                                        },
                                    },
                                ],
                            },
                        },
                    ],
                },
                toolbarConfig: {
                    refresh: true,
                    export: proxy.$auth.hasPermi("system:role:export"),
                    // print: true,
                    zoom: true,
                    custom: true,
                    printDesign: {
                        setPrintTemplate: true,
                        previewPrint: true,
                        directPrint: true,
                        setPrintTemplateConfig: {
                            // status: "success",
                            disabled: false,
                            content: "设置模板",
                            size: "medium",
                            // 点击按钮时调用，返回true时打开设计页面反之不打开
                            beforeClick: () => {
                                return true;
                            },
                            // 拖拽面板查询接口
                            queryProvider: () => {
                                return callGetOnePro(1).then((response) => {
                                    console.log("拖拽面板查询接口", JSON.parse(response.data?.providerData));
                                    return { data: JSON.parse(response.data?.providerData) };
                                });
                            },
                            // 模板查询接口，返回模板数据
                            queryPanel: () => {
                                return callGetOne(1).then((response) => {
                                    console.log("模板查询接口", response);
                                    return { data: JSON.parse(response.data?.panelData) };
                                });
                            },
                            // 保存模板时调用接口
                            saveDesign: (data: any) => {
                                console.log("保存模板数据", data);
                                return callModify(data).then((response) => {
                                    // return { data: { b: "b" } };
                                });
                            },
                        },
                        // 预览打印和直接打印的公共接口（优先使用预览打印和直接调用中的接口）
                        printApi: {
                            queryPanel: () => {
                                return callGetOne(1).then((response) => {
                                    return { data: JSON.parse(response.data?.panelData) };
                                });
                            },
                            // 打印数据查询接口
                            queryPrintData: () => {
                                return callGetOnePro(1).then((response) => {
                                    return response;
                                });
                            },
                        },
                        previewPrintConfig: {
                            // status: "success",
                            content: "预览打印",
                            // 模板查询接口
                            queryPanel: () => {
                                return callGetOne(2).then((response) => {
                                    console.log("模板查询接口", response);
                                    return { data: JSON.parse(response.data?.panelData) };
                                });
                            },
                            // 打印数据查询接口
                            queryPrintData: () => {
                                return callGetOnePro(1).then((response) => {
                                    return { data: { recimprestno: "b" } };
                                });
                            },
                            params: {
                                printerName: "测试",
                                printTitle: "测试",
                            },
                        },
                        directPrintConfig: {
                            // status: "success",
                            content: "直接打印",
                            // 模板查询接口
                            queryPanel: () => {
                                return callGetOne(1).then((response) => {
                                    return { data: { b: "b" } };
                                });
                            },
                            // 打印数据查询接口
                            queryPrintData: () => {
                                return pageRole({}).then((response) => {
                                    return { data: { b: "b" } };
                                });
                            },
                        },
                    },
                    slots: {
                        tools: "toolbar_tools",
                        buttons: "toolbar_buttons",
                    },
                },
                proxyConfig: {
                    paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
                    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
                    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
                    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
                    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
                    // 对应响应结果 { result: [], page: { total: 100 } }
                    props: {
                        result: "rows", // 配置响应结果列表字段
                        total: "total", // 配置响应结果总页数字段
                    },
                    ajax: {
                        // 接收 Promise
                        query: ({ page, sorts, filters, form, params }: any) => {
                            // 处理时间范围查询
                            const createTime = proxy.addDateRange({}, form.createTime, "createTime");
                            const queryParams: any = Object.assign({}, form, createTime, page, params);
                            // 处理排序条件
                            const orderByColumn = <Array<String>>[];
                            const isAsc = <Array<Boolean>>[];
                            sorts.forEach((m: any) => {
                                orderByColumn.push(m.field);
                                isAsc.push(m.order);
                            });
                            queryParams.orderByColumn = orderByColumn.join(",");
                            queryParams.isAsc = isAsc.join(",");
                            // 处理筛选条件
                            filters.forEach(({ property, values }: any) => {
                                queryParams[property] = values.join(",");
                            });
                            return pageRole({
                                ...removeObjectNull(queryParams),
                            }).then((response) => {
                                return response;
                            });
                        },
                    },
                },
                columns: [
                    { type: "checkbox", width: 60, fixed: "left" },
                    {
                        field: "roleId",
                        title: "角色编号",
                        sortable: true,
                    },
                    {
                        field: "roleName",
                        title: "角色名称",
                        sortable: true,
                    },
                    {
                        field: "roleKey",
                        title: "权限字符",
                        sortable: true,
                    },
                    {
                        field: "roleSort",
                        title: "显示顺序",
                        sortable: true,
                    },
                    {
                        field: "dataScope",
                        title: "数据范围",
                        sortable: true,
                        editRender: {
                            name: "select",

                            options: [
                                {
                                    value: 1,
                                    label: "所有数据权限",
                                },
                                {
                                    value: 2,
                                    label: "自定义数据权限",
                                },
                                {
                                    value: 3,
                                    label: "本部门数据权限",
                                },
                                {
                                    value: 4,
                                    label: "本部门及以下数据权限",
                                },
                                {
                                    value: 5,
                                    label: "仅本人数据权限",
                                },
                                {
                                    value: 6,
                                    label: "自定义语句",
                                },
                            ],
                            props: {
                                visible: false,
                            },
                        },
                    },
                    {
                        field: "status",
                        title: "状态",
                        filters: sys_normal_disable,
                        slots: {
                            default: "slotStatus",
                        },
                    },
                    {
                        field: "createTime",
                        title: "创建时间",
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        title: "操作",
                        width: 200,
                        align: "center",
                        fixed: "right",
                        slots: { default: "action" },
                    },
                ],
                exportConfig: {
                    filename: "角色数据",
                    remote: true,
                    types: ["xlsx"],
                    modes: ["current", "selected", "all"],
                    isHeader: true,
                    // isFooter: false,
                    // isColgroup: true,
                    // isMerge: true,
                    // isAllExpand: true,
                    useStyle: true,
                    // original: true,
                    // 自定义服务端导出
                    exportMethod({ options }) {
                        const $grid = xGrid.value;
                        const proxyInfo = $grid.getProxyInfo();
                        console.log("11111111111111", proxyInfo, options);
                        //排序处理
                        const orderByColumn = <Array<String>>[];
                        const isAsc = <Array<Boolean>>[];
                        proxyInfo?.sorts.forEach((m: any) => {
                            orderByColumn.push(m.field);
                            isAsc.push(m.order);
                        });

                        // 传给服务端的参数
                        const body = {
                            filename: options.filename,
                            sheetName: options.sheetName,
                            isHeader: options.isHeader,
                            isFooter: options.isFooter,
                            original: options.original,
                            isColgroup: options.isColgroup,
                            isMerge: options.isMerge,
                            isAllExpand: options.isAllExpand,
                            useStyle: options.useStyle,
                            mode: options.mode,
                            ...proxyInfo.pager,
                            ids: options.mode === "selected" ? options.data.map((item: any) => item.roleId) : [],
                            fields: options.columns.map((column: any) => {
                                return {
                                    field: column.property,
                                    title: column.title,
                                };
                            }),
                            // 查询条件
                            query: proxyInfo?.form,
                            // 排序
                            sort: proxyInfo?.sort,
                            orderByColumn: orderByColumn.join(","),
                            isAsc: isAsc.join(","),
                        };
                        // 开始服务端导出
                        return VxeDownload("system/role/exportVxe", body, options.filename ? options.filename + `.${options.type}` : `用户数据${new Date().getTime()}.${options.type}`);
                    },
                },
                checkboxConfig: {
                    labelField: "id",
                    reserve: true,
                    highlight: true,
                    range: true,
                    trigger: "row",
                },
                editConfig: {
                    enabled: false,
                },
            });

            const gridEvents: VxeGridListeners = {
                zoom({ type }) {
                    console.log(`表格全屏 type=${type}`);
                },
                toolbarButtonClick(code) {
                    console.log("toolbarButtonClick", code);
                },
                toolbarToolClick(code) {
                    console.log("toolbarToolClick", code);
                },
                resizableChange(code) {
                    console.log("列宽", code);
                },
            };

            function onCustom({ data, type }: VxeGridDefines.CustomEventParams) {
                if (type === "confirm" || type === "reset") {
                    xGrid.value.setColumnIndex(data);
                }
            }

            /** 多选框选中数据 */
            function handleSelectionChange(data: any) {
                single.value = data.records.length != 1;
                multiple.value = !data.records.length;
            }

            /** 添加角色 */
            function handleAdd() {
                isUpdate.value = false;
                recordRole.value = {};
                roleModalVisible.value = true;
            }
            /** 修改角色 */
            function handleUpdate(row: any) {
                const roleId = row?.roleId || getTableAction().getCheckboxRecords()[0]?.roleId;
                const roleMenu = getRoleMenuTreeselect(roleId);
                getRole(roleId).then((response: any) => {
                    const form = {
                        ...response.data,
                        roleSort: Number(response.data.roleSort),
                    };
                    recordRole.value = {
                        form: form,
                        roleMenu: roleMenu,
                    };
                    isUpdate.value = true;
                    roleModalVisible.value = true;
                });
            }

            /** 根据角色ID查询菜单树结构 */
            function getRoleMenuTreeselect(roleId: any) {
                return roleMenuTreeselect(roleId).then((response: any) => {
                    return response;
                });
            }

            /** 分配数据权限操作 */
            function handleDataScope(row: any) {
                const deptTreeSelect = getDeptTree(row?.roleId);
                getRole(row?.roleId).then((response) => {
                    recordDataScope.value = {
                        form: response.data,
                        deptTreeSelect: deptTreeSelect,
                    };
                    openDataScope.value = true;
                });
            }
            /** 自定义数据权限*/
            function handleCustomDataScope(row: any) {
                router.push("/system/custom-dataScope/index/" + row.roleId);
            }
            /** 根据角色ID查询部门树结构 */
            function getDeptTree(roleId: any) {
                return deptTreeSelect(roleId).then((response: any) => {
                    deptOptions.value = response.depts;
                    return response;
                });
            }
            /** 分配用户 */
            function handleAuthUser(row: any) {
                router.push("/system/role-auth/user/" + row.roleId);
            }
            /** 表格配置 */
            function handleTableEdit(row: any) {
                router.push("/system/role-table/table/" + row.roleId);
            }
            /** 删除按钮操作 */
            async function handleDelete(row: any) {
                const list = await getTableAction().getCheckboxRecords();
                const roleIds = row.roleId || list.map((item: any) => item.roleId);
                proxy.$modal
                    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
                    .then(function () {
                        return delRole(roleIds);
                    })
                    .then(() => {
                        xGrid.value.commitProxy("reload");
                        proxy.$modal.msgSuccess("删除成功");
                    })
                    .catch(() => {});
            }
            /**
             * 关闭新增/修改弹窗
             * @param data
             */
            function closeRole(data: any) {
                roleModalVisible.value = false;
                if (data?.type == "submit") {
                    xGrid.value.commitProxy("reload");
                }
            }
            function closeDataScope(data: any) {
                openDataScope.value = false;
                if (data?.type == "submit") {
                    getTableAction().commitProxy("reload");
                }
            }

            /** 角色状态修改 */
            function handleStatusChange(row: any) {
                let text = row.status === "0" ? "启用" : "停用";
                proxy.$modal
                    .confirm('确认要"' + text + '" "' + row.roleName + '"角色吗?')
                    .then(function () {
                        return changeRoleStatus(row.roleId, row.status);
                    })
                    .then(() => {
                        proxy.$modal.msgSuccess(text + "成功");
                        getTableAction().commitProxy("reload");
                    })
                    .catch(function () {
                        row.status = row.status === "0" ? "1" : "0";
                    });
            }
            const dateRange = ref<any>([]);

            return {
                xGrid,
                gridOptions,
                gridEvents,
                searchInfo,
                dateRange,
                isUpdate,
                handleAdd,
                handleUpdate,
                roleModalVisible,
                recordRole,
                recordDataScope,
                single,
                multiple,
                handleSelectionChange,
                closeRole,
                closeDataScope,
                handleDelete,
                handleDataScope,
                handleAuthUser,
                deptOptions,
                openDataScope,
                handleStatusChange,
                proxy,
                handleTableEdit,
                onCustom,
                handleCustomDataScope,
            };
        },
    });
</script>
